package anton.admin.schema;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Resource;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.sql.DataSource;

@ManagedBean(name = "empBean")
@RequestScoped
public class EmpBean {

    @Resource(name = "jdbc/antonsDatasource")
    private DataSource ds;
    List<Employee> emps;

    public List<Employee> getEmps() {
        return emps;
    }

    public void setEmps() throws SQLException {
        Connection con = null;
        PreparedStatement ps = null;
        ResultSet result = null;
        emps.clear();

        try {
            if (ds == null) {
                throw new SQLException("Can't get data source");
            }

            con = ds.getConnection();

            if (con == null) {
                throw new SQLException("Can't get database connection");
            }

            ps = con.prepareStatement("SELECT * FROM Employees");

            result = ps.executeQuery();

            while (result.next()) {
                Employee temp = new Employee();

                temp.setUsername(result.getString("username"));
                temp.setEmp_name(result.getString("emplyee_name"));

                emps.add(temp);
            }
        } finally {
            closeAll(result, ps, con);
        }
    }

    public void firstSetEmps() throws SQLException {
        if (emps.isEmpty()) {
            setEmps();
        }
    }
    
    public void update(boolean updated) throws SQLException{
        if(updated)
        {
            setEmps();
        }
    }

    public EmpBean() {
        emps = new ArrayList<>();
    }

    private static void closeAll(ResultSet resultSet, PreparedStatement preState, Connection con) {
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
            }
        }
        if (preState != null) {
            try {
                preState.close();
            } catch (SQLException e) {
            }
        }
        if (con != null) {
            try {
                con.close();
            } catch (SQLException e) {
            }
        }
    }
}
